import qs from "qs"
import axios from "axios"
import mui from "../assets/mui/js/mui.js"

//let baseUrl1 = "/api" //设置你的baseUr
let baseUrl1 = "https://a.youzhijungroup.com/" //设置你的baseUr
let baseUrl2 = "https://pigx.youzhijungroup.com/admin" //设置你的baseUr     小程序  wx28f6ba719c90df5b    c4d404bd541c84b7b0352f6887c31331

//封装请求方法
function formatReq(type, url, data,baseUrl,contentType) {
  let headers = {
    "content-Type": contentType,
    "Authorization": localStorage.getItem('Authorization')
  };
  return new Promise((reslove, reject) => {
    axios({
      method: type,
      url: `${baseUrl}${url}`,
      headers: headers,
      data: contentType=='application/json' ? data : qs.stringify(data)
    })
      .then(r => {
        reslove(r.data);
      })
      .catch(e => {
        let result = e.response.data.result || e.response.data || e.response || e;
        //result && mui.toast(result);
        mui.toast(JSON.stringify(result));
        reject('');
      });
  });
}
function get(url, query,baseUrl) {
  let author = localStorage.getItem('Authorization');
  let headers = {};
  author && (headers.Authorization = author);
  return axios.get(`${baseUrl}${url}`, { params: query,headers: headers}).then(r => r.data).catch( (error) => {});;
}
function extend(from,to){
  for(var key in to){
    from[key] = to[key];
  }
}
function trim(str){
  return str.replace(/^\s*|\s*$/g,"");
}
function cookie(name, value, options) {
  if (value && typeof value != 'undefined') {
      options = options || {};
      if (!options.expires) {
          options.expires = 7;
      }
      var expires = '';
      if (options.expires && (typeof options.expires == 'number'
                              || options.expires.toUTCString)) {
          var date;
          if (typeof options.expires == 'number') {
              date = new Date();
              date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
          } else {
              date = options.expires;
          }
          expires = '; expires=' + date.toUTCString();
      }
      var path = options.path ? '; path=' + (options.path) : '; path=/';
      var domain = options.domain ? '; domain=' + (options.domain) : '';
      var secure = options.secure ? '; secure' : '';
      document.cookie =
          [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  } else {
      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
              var cookie = trim(cookies[i]);
              var subs = cookie.substring(0, name.length + 1);
              if ( subs== (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
  }
}
const Http = {
  uploadUrl: `${baseUrl1}yzj/image/upload`,
  cookie: cookie,
  get: (url, query) => get(url, query,baseUrl1),
  jsonpost: (url, data) => formatReq("post", url, data,baseUrl1,"application/json"),
  jsonput: (url, data) => formatReq("put", url, data,baseUrl1,"application/json"),
  post: (url, data) => formatReq("post", url, data,baseUrl1,"application/x-www-form-urlencoded"),
  put: (url, data) => formatReq("put", url, data,baseUrl1,"application/x-www-form-urlencoded"),
  delete: (url, data) => formatReq("delete", url, data,baseUrl1,"application/x-www-form-urlencoded"),
  getUrlParam: (name,url) => {
    var str = url || window.location.search || window.location.hash,
    result = null;
    if (!name || str === '') {
        return result;
    }
    result = str.match(new RegExp('(^|&|[\?#])' + name + '=([^&]*)(&|$)')); 
    return result === null ? result : decodeURIComponent(result[2]);
  },
  orginupload: (file) =>{
    return new Promise((resolve,reject)=>{
      let formData = new FormData()
      // 自定义formData中的内容
      formData.append('photo_img', file)
      let xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) { // 上传成功
            let result = JSON.parse(xhr.responseText);
            resolve(result.id);
          }else{
            reject();
          }
        }
      }
      xhr.open('POST', `${baseUrl1}yzj/image/upload`, true);
      xhr.setRequestHeader("Authorization",localStorage.getItem('Authorization'));
      xhr.send(formData)
    })
  },
  imgpre: 'http://a.youzhijungroup.com/yzj/image/download/'
}
const Http2 = {
  get: (url, query) => get(url, query,baseUrl2),
  put: (url, data) => formatReq("put", url, data,baseUrl2,"application/x-www-form-urlencoded"),
  jsonpost: (url, data) => formatReq("post", url, data,baseUrl2,"application/json"),
  jsonput: (url, data) => formatReq("put", url, data,baseUrl2,"application/json"),
  post: (url, data) => formatReq("post", url, data,baseUrl2,"application/x-www-form-urlencoded"),
  delete: (url, data) => formatReq("delete", url, data,baseUrl2,"application/x-www-form-urlencoded")
}

export {Http,Http2};
